/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PatientPhoneInformationPanel.java
 *
 * Created on Aug 13, 2011, 3:58:01 PM
 */
package panels;

import conn.EMIS4Connection;
import dao.PhoneDao;
import dao.PhoneTypeDao;
import dao.UpdateHistoryDao;
import exec.NotFoundException;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import main.MainFrame;
import obj.Phone;
import obj.PhoneType;
import obj.UpdateHistory;
import util.EMISUtil;
import util.PersonRequested;

/**
 *
 * @author NATHAN
 */
public class PatientPhoneInformationPanel extends javax.swing.JPanel {

  private EMIS4Connection conn;
  private PersonRequested pr = PersonRequested.getInstance();
  private Phone primaryPhone;
  private Phone secondaryPhone;
  private PhoneDao phoneDAO;
  private List<Phone> phoneList;
  private PhoneTypeDao phoneTypeDAO;
  private List<PhoneType> phoneTypeList;
  private UpdateHistory history;
  private UpdateHistoryDao historyDAO;
  private int personID;

  /** Creates new form PatientPhoneInformationPanel */
  public PatientPhoneInformationPanel() {
    conn = EMIS4Connection.getInstance();
    primaryPhone = new Phone();
    secondaryPhone = new Phone();
    phoneDAO = new PhoneDao();
    phoneTypeDAO = new PhoneTypeDao();
    history = new UpdateHistory();
    historyDAO = new UpdateHistoryDao();

    initComponents();

    fillInformation();
  }

  private void fillInformation() {
    personID = pr.getPerson().getPersonID();
    primaryPhone.setPersonID(personID);

    try {
      // get info from database
      conn.connect();
      phoneList = phoneDAO.searchMatching(conn.getConnection(), primaryPhone);
      phoneTypeList = phoneTypeDAO.loadAll(conn.getConnection());
    } catch (SQLException ex) {
      Logger.getLogger(RegisterPanel.class.getName()).log(Level.SEVERE, null, ex);
    }

    // fill out combo boxes
    for (PhoneType phoneItem : phoneTypeList) {
      primaryPhoneComboBox.addItem(phoneItem.getTitle());
      secondaryPhoneComboBox.addItem(phoneItem.getTitle());
    }

    // fill out info
    switch (phoneList.size()) {
      case 2:
        // fill out second number
        secondaryPhone = phoneList.get(1);
        secondaryPhoneTextField.setText(EMISUtil.convertPhoneString(secondaryPhone.getNumber()));
        //secondaryPhoneTextField.setEnabled(secondaryPhone.getActive());
        secondaryPhoneComboBox.setSelectedIndex(secondaryPhone.getPhoneTypeID());
      case 1:
        // fill out first number
        primaryPhone = phoneList.get(0);
        primaryPhoneTextField.setText(EMISUtil.convertPhoneString(primaryPhone.getNumber()));
        //primaryPhoneTextField.setEnabled(primaryPhone.getActive());
        primaryPhoneComboBox.setSelectedIndex(primaryPhone.getPhoneTypeID());
    }
  }

  private void popupWarning(String msg) {
    warningLabel.setText(msg);
    warningDialog.pack();
    warningDialog.setLocationRelativeTo(MainFrame.getInstance());
    warningDialog.setVisible(true);
  }

  /** This method is called from within the constructor to
   * initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is
   * always regenerated by the Form Editor.
   */
  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {
    java.awt.GridBagConstraints gridBagConstraints;

    warningDialog = new javax.swing.JDialog();
    warningLabel = new javax.swing.JLabel();
    okButton = new javax.swing.JButton();
    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    jLabel3 = new javax.swing.JLabel();
    primaryPhoneComboBox = new javax.swing.JComboBox();
    secondaryPhoneComboBox = new javax.swing.JComboBox();
    submitButton = new javax.swing.JButton();
    primaryPhoneTextField = new javax.swing.JFormattedTextField();
    secondaryPhoneTextField = new javax.swing.JFormattedTextField();

    warningDialog.setTitle("Warning!");
    warningDialog.setAlwaysOnTop(true);
    warningDialog.setModal(true);
    warningDialog.getContentPane().setLayout(new java.awt.GridBagLayout());

    warningLabel.setText("Message goes here");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.insets = new java.awt.Insets(10, 15, 10, 15);
    warningDialog.getContentPane().add(warningLabel, gridBagConstraints);

    okButton.setText("OK");
    okButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        okButtonActionPerformed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.insets = new java.awt.Insets(0, 0, 10, 0);
    warningDialog.getContentPane().add(okButton, gridBagConstraints);

    setBackground(new java.awt.Color(220, 220, 210));
    setLayout(new java.awt.GridBagLayout());

    jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24));
    jLabel1.setText("Phone Information");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 0;
    gridBagConstraints.gridwidth = 3;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    gridBagConstraints.insets = new java.awt.Insets(20, 15, 10, 20);
    add(jLabel1, gridBagConstraints);

    jLabel2.setText("Primary Phone:");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    gridBagConstraints.insets = new java.awt.Insets(10, 30, 0, 0);
    add(jLabel2, gridBagConstraints);

    jLabel3.setText("Secondary Phone:");
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = 2;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    gridBagConstraints.insets = new java.awt.Insets(10, 30, 0, 0);
    add(jLabel3, gridBagConstraints);

    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 2;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    gridBagConstraints.insets = new java.awt.Insets(6, 10, 0, 10);
    add(primaryPhoneComboBox, gridBagConstraints);

    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 2;
    gridBagConstraints.gridy = 2;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    gridBagConstraints.insets = new java.awt.Insets(6, 10, 0, 10);
    add(secondaryPhoneComboBox, gridBagConstraints);

    submitButton.setText("Submit");
    submitButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        submitButtonActionPerformed(evt);
      }
    });
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 2;
    gridBagConstraints.gridy = 3;
    gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_START;
    gridBagConstraints.weightx = 0.1;
    gridBagConstraints.weighty = 0.1;
    gridBagConstraints.insets = new java.awt.Insets(20, 0, 15, 15);
    add(submitButton, gridBagConstraints);

    try {
      primaryPhoneTextField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("(###) ###-####")));
    } catch (java.text.ParseException ex) {
      ex.printStackTrace();
    }
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 1;
    gridBagConstraints.gridy = 1;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    gridBagConstraints.insets = new java.awt.Insets(6, 10, 0, 0);
    add(primaryPhoneTextField, gridBagConstraints);

    try {
      secondaryPhoneTextField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("(###) ###-####")));
    } catch (java.text.ParseException ex) {
      ex.printStackTrace();
    }
    gridBagConstraints = new java.awt.GridBagConstraints();
    gridBagConstraints.gridx = 1;
    gridBagConstraints.gridy = 2;
    gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
    gridBagConstraints.insets = new java.awt.Insets(6, 10, 0, 0);
    add(secondaryPhoneTextField, gridBagConstraints);
  }// </editor-fold>//GEN-END:initComponents

private void submitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_submitButtonActionPerformed
// TODO add your handling code here:
  String oldValue, newValue;

  try {
    conn.connect();

    if (phoneList.isEmpty()) {
      // no existing numbers
      newValue = primaryPhoneTextField.getText().replaceAll("[^0-9]", "");
      if (!("".equals(newValue)) && primaryPhoneComboBox.getSelectedIndex() != 0) {
        // new primary phone
        primaryPhone.setAll(personID, newValue, primaryPhoneComboBox.getSelectedIndex(), true);
        phoneDAO.create(conn.getConnection(), primaryPhone);
        history.setAll("Phone", primaryPhone.getPhoneID(), "New Entry", "New primary phone number", "", newValue);
        historyDAO.create(conn.getConnection(), history);
      }
      newValue = secondaryPhoneTextField.getText().replaceAll("[^0-9]", "");
      if (!("".equals(newValue)) && secondaryPhoneComboBox.getSelectedIndex() != 0) {
        // new secondary phone
        secondaryPhone.setAll(personID, newValue, secondaryPhoneComboBox.getSelectedIndex(), true);
        phoneDAO.create(conn.getConnection(), secondaryPhone);
        history.setAll("Phone", secondaryPhone.getPhoneID(), "New Entry", "New secondary phone number", "", newValue);
        historyDAO.create(conn.getConnection(), history);
      }
    } else if (phoneList.size() == 1) {
      // 1 existing number
      oldValue = primaryPhone.getNumber();
      newValue = primaryPhoneTextField.getText().replaceAll("[^0-9]", "");
      if (!(oldValue.equals(newValue))) {
        // primary number changed
        primaryPhone.setNumber(newValue);
        primaryPhone.setPhoneTypeID(primaryPhoneComboBox.getSelectedIndex());
        phoneDAO.save(conn.getConnection(), primaryPhone);
        history.setAll("Phone", primaryPhone.getPhoneID(), "Number", "Primary phone number changed", oldValue, newValue);
        historyDAO.create(conn.getConnection(), history);
      }
      newValue = secondaryPhoneTextField.getText().replaceAll("[^0-9]", "");
      if (!("".equals(newValue)) && secondaryPhoneComboBox.getSelectedIndex() != 0) {
        // new secondary phone
        secondaryPhone.setAll(personID, newValue, secondaryPhoneComboBox.getSelectedIndex(), true);
        phoneDAO.create(conn.getConnection(), secondaryPhone);
        history.setAll("Phone", secondaryPhone.getPhoneID(), "New Entry", "New secondary phone number", "", newValue);
        historyDAO.create(conn.getConnection(), history);
      }
    } else if (phoneList.size() == 2) {
      // 2 existing numbers
      oldValue = primaryPhone.getNumber();
      newValue = primaryPhoneTextField.getText().replaceAll("[^0-9]", "");
      if (!(oldValue.equals(newValue))) {
        // primary number changed
        primaryPhone.setNumber(newValue);
        primaryPhone.setPhoneTypeID(primaryPhoneComboBox.getSelectedIndex());
        phoneDAO.save(conn.getConnection(), primaryPhone);
        history.setAll("Phone", primaryPhone.getPhoneID(), "Number", "Primary phone number changed", oldValue, newValue);
        historyDAO.create(conn.getConnection(), history);
      }
      oldValue = secondaryPhone.getNumber();
      newValue = secondaryPhoneTextField.getText().replaceAll("[^0-9]", "");
      if (!(oldValue.equals(newValue))) {
        // secondary number changed
        secondaryPhone.setNumber(newValue);
        secondaryPhone.setPhoneTypeID(secondaryPhoneComboBox.getSelectedIndex());
        phoneDAO.save(conn.getConnection(), secondaryPhone);
        history.setAll("Phone", secondaryPhone.getPhoneID(), "Number", "Primary phone number changed", oldValue, newValue);
        historyDAO.create(conn.getConnection(), history);
      }
    }
  } catch (NotFoundException ex) {
    Logger.getLogger(PatientPhoneInformationPanel.class.getName()).log(Level.SEVERE, null, ex);
  } catch (SQLException ex) {
    Logger.getLogger(PatientPhoneInformationPanel.class.getName()).log(Level.SEVERE, null, ex);
  }

  warningDialog.setTitle("Success");
  popupWarning("Changes saved.");
}//GEN-LAST:event_submitButtonActionPerformed

private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
  warningDialog.setVisible(false);
}//GEN-LAST:event_okButtonActionPerformed
  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JLabel jLabel1;
  private javax.swing.JLabel jLabel2;
  private javax.swing.JLabel jLabel3;
  private javax.swing.JButton okButton;
  private javax.swing.JComboBox primaryPhoneComboBox;
  private javax.swing.JFormattedTextField primaryPhoneTextField;
  private javax.swing.JComboBox secondaryPhoneComboBox;
  private javax.swing.JFormattedTextField secondaryPhoneTextField;
  private javax.swing.JButton submitButton;
  private javax.swing.JDialog warningDialog;
  private javax.swing.JLabel warningLabel;
  // End of variables declaration//GEN-END:variables
}
